/*
 * This file is a part of qloudgen-esb. 
 * You can redistribute qloudgen-esb and/or modify it under the terms of the Lesser GNU General Public License version 3. 
 * qloudgen-esb is distributed WITHOUT ANY WARRANTY. 
 * 
 * See the Lesser GNU General Public License for more details at http://www.gnu.org/licenses/.
 *  
 * Copyright (C) 2014 Qloudgen Technology
*/

package com.qloudgen.csb;

import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;

public class CSBServerBase {
	private int perfInterval;
	
	private final Lock lock = new ReentrantLock();	
	private HashMap<String, Long> counts = new HashMap<String, Long>();
	private HashMap<String, Long> tps = new HashMap<String, Long>();

    private static Logger LOG = Logger.getLogger(CSBServerBase.class.getName());
	
    public CSBServerBase(int perfInterval) {
    	this.perfInterval = perfInterval;
    }

    public HashMap<String, Long> getTPS() {
    	HashMap<String, Long> data = null;
    	try {
			if (lock.tryLock(100L, TimeUnit.MILLISECONDS))
				data = new HashMap<String, Long>(tps);
		} catch (InterruptedException e) {
			LOG.warn("getTPS() interrupted, null returned...");
    	} finally {
    		lock.unlock();
    	}
    	return data;
    }
    
    protected void perf() {
    	new Thread(new Runnable() {
			@Override
			public void run() {	
				while (true) {
					counts.clear();
					long t = System.currentTimeMillis();
					try {
						Thread.sleep(perfInterval);
					} catch (InterruptedException e) {}	
					lock.lock();
					try {
						tps.clear();
						Iterator<String> itr = counts.keySet().iterator();
						while (itr.hasNext()) {
							String s = itr.next();
							tps.put(s, counts.get(s)*1000
								/(System.currentTimeMillis() - t));
						}
					} finally {
						lock.unlock();
					}
				}
			}    		    		
    	}).start();    	
    }
    
    protected void mark(String s) {
    	Long c = counts.get(s);
    	if (c == null)
    		c = 0L;
    	counts.put(s, ++c);
    }
}

